package com.zzyl.framework.interceptor;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserId implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");

        //获取token
        if (token == null) {
            throw new BaseException("用户认证失败");
        }

        //解释一下token
        Claims claims = tokenService.parseToken(token);
        if (ObjectUtils.isEmpty(claims)) {
            throw new BaseException("用户认证失败");
        }
        //id
        Long userId = claims.get("id", Long.class);
        if (ObjectUtils.isEmpty(userId)) {
            throw new BaseException("用户认证失败");
        }
            //把数据存储到线程中
        UserThreadLocal.set(userId);
        return true;


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
